<template>
  <div
    v-loading="
      processFlg || deviceFlg || clampFlg || personnelFlg || saveLoading
    "
    element-loading-text="数据加载中..."
    class="container-box"
  >
    <el-form
      :model="form"
      :rules="rules"
      label-width="120px"
      class="form"
      ref="ruleForm"
    >
      <el-form-item label="产线模板名称" prop="realityLineName">
        <!-- <span>产线模板名称：</span> -->
        <el-input
          v-model="form.realityLineName"
          placeholder="请输入"
          style="width: 200px; margin-right: 5px"
        ></el-input>
      </el-form-item>
      <el-form-item label="产线类型" prop="lineType">
        <el-select
          v-model="form.lineType"
          placeholder="请选择产线类型"
          filterable
          clearable
          style="width: 200px; margin-right: 5px"
        >
          <el-option
            v-for="item in line_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品分类" prop="productCategory">
        <el-select
          v-model="form.productCategory"
          placeholder="请选择产品分类"
          filterable
          clearable
          style="width: 200px; margin-right: 5px"
          label="产品分类"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.productCategory"
            :value="item.productCategory"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="线平衡率" prop="lineIndicator">
        <el-input
          v-model="form.lineIndicator"
          type="number"
          placeholder="请输入数字，最多两位小数"
          style="width: 200px; margin-right: 5px"
          @change="handleLineIndicatorChange"
        ></el-input>
      </el-form-item>
      <!-- <span style="margin-left: 20px">：</span> -->

      <!-- <span style="margin-left: 20px">产线类型：</span> -->

      <!-- <el-button
          type="primary"
          style="margin-left: 100px"
          @click="downloadTemplate"
          >模版下载</el-button
        > -->
      <!-- <el-button type="primary" @click="importExcel">Excel快速导入</el-button> -->
    </el-form>
    <div class="table-box">
      <el-table :data="tableList" border :height="availableHeight" width="100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="工位" prop="workPositionName"></el-table-column>
        <el-table-column label="工序名称">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <!-- <el-select
                v-model="item.processId"
                placeholder="请选择"
                filterable
                @change="changeProcess(scope.row)"
                clearable
              >
                <el-option
                  v-for="(item, index) in processList"
                  :key="index"
                  :label="item.processName"
                  :value="item.id"
                ></el-option>
              </el-select> -->
              <div>{{ item.processName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设备类型">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
<!--              <el-select
                v-model="item.deviceTypeArray"
                placeholder="请选择"
                @focus="scope.row.deviceShowOption = true"
                @blur="scope.row.deviceShowOption = false"
                multiple
                filterable
                clearable
              >
                <el-option
                  v-for="(item, index) in deviceList"
                  :key="index"
                  :label="`${item.deviceName} `"
                  :value="item.deviceName"
                ></el-option>
              </el-select>-->
              <elSelectTpl :list="deviceList" :isCollapsed="true" v-model="item.deviceTypeArray" :selectedValues="item.deviceTypeArray" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设备数量">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <el-input v-model="item.deviceNum" type="number" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工具类型">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
<!--              <el-select
                v-model="item.toolTypeArray"
                placeholder="请选择"
                @focus="scope.row.deviceShowOption = true"
                @blur="scope.row.deviceShowOption = false"
                multiple
                filterable
                clearable
              >
                <el-option
                  v-for="(item, index) in toolList"
                  :key="index"
                  :label="`${item.deviceName} `"
                  :value="item.deviceName"
                ></el-option>
              </el-select>-->
              <elSelectTpl :list="toolList" :isCollapsed="true" v-model="item.toolTypeArray" :selectedValues="item.toolTypeArray" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工具数量">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <el-input v-model="item.toolNum" type="number" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="夹具类型">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
<!--              <el-select
                v-model="item.clampTypeArray"
                placeholder="请选择"
                @focus="scope.row.deviceShowOption = true"
                @blur="scope.row.deviceShowOption = false"
                multiple
                filterable
                clearable
              >
                <el-option
                  v-for="(item, index) in clampList"
                  :key="index"
                  :label="`${item.deviceName} `"
                  :value="item.deviceName"
                ></el-option>
              </el-select>-->
              <elSelectTpl :list="clampList" :isCollapsed="true" v-model="item.clampTypeArray" :selectedValues="item.clampTypeArray" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="夹具数量">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <el-input v-model="item.clampNum" type="number" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="资质等级" min-width="100">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <el-select
                v-model="item.personGradesArray"
                placeholder="请选择"
                @focus="scope.row.deviceShowOption = true"
                @blur="scope.row.deviceShowOption = false"
                multiple
                collapse-tags
                filterable
                clearable
              >
                <el-option
                  v-for="(item, index) in person_grades"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="人员数量">
          <template slot-scope="scope">
            <div
              v-for="(item, i) in scope.row.workPositionDataList"
              :key="i"
              style="margin-bottom: 10px"
            >
              <el-input v-model="item.personNum" type="number" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button size="mini" @click="moveUp(scope.$index)"
              >上移</el-button
            >
            <el-button size="mini" @click="moveDown(scope.$index)"
              >下移</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="deleteRow(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-button type="primary" @click="addRow">添加工位</el-button>
      <el-button type="primary" @click="save('ruleForm')">保存</el-button>
      <el-button type="button" class="my-cancel-button" @click="handleClose"
        >取消</el-button
      >
    </div>

    <el-dialog
      title="添加工位"
      :visible.sync="editWorkVisible"
      append-to-body
      width="30%"
    >
      <el-form :model="workform" :rules="rules" ref="workruleForm">
        <el-form-item label="工位名称" prop="station" label-position="left">
          <el-select
            v-model="workform.station"
            placeholder="请选择工位"
            multiple
            filterable
            clearable
            style="width: 80%"
          >
            <el-option
              v-for="(item, index) in workPositionList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editWorkVisible = false">取 消</el-button>
        <el-button type="primary" @click="preAddstation">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import XLSX from 'xlsx'
const XLSX = require("xlsx");
import { getObj } from "@/api/pfoc/factorysettings"; //获取当前工厂信息
import {
  getDevice,
  getNewDevice,
  getPersonGrades,
  getLineType,
} from "@/api/hengdong/pfocinterface"; //获取设备相关
import { getWorkshopList } from "@/api/pfoc/workshop"; //获取全部车间
import { getPersonCredentialList } from "@/api/workorder/personcredentialmanage";
import { getCategory } from "@/api/workorder/hdviewapiitem"; //获取品类
import { getPfocProcessList } from "@/api/pfoc/pfocprocess";
import { saveProductLine } from "@/api/pfoc/realityproductlinemain";
import { downBlobFile } from "@/util/index";
import ElSelectLineTpl from "@/components/select/el-select-linemodeling-tpl.vue";

import {
  putObj,
  addObj,
  getAllObj,
} from "@/api/pfoc/realityproducelinemodeling";

import { getWorkPositionList } from "@/api/common.js";
import { getWorkPositionData } from "@/api/pfoc/workposition.js";

export default {
  components: { elSelectTpl: ElSelectLineTpl },
  data() {
    return {
      form: {
        realityLineName: "",
        lineType: "",
        productCategory: "",
        lineIndicator: "",
      },
      tableData: [],
      tableList: [],
      workshopList: [],
      workshopId: null, // 存储选中的车间ID
      processList: [],
      workPositionList: [],
      categoryList: [],
      category: null,
      deviceList: [],
      clampList: [],
      toolList: [],
      personCredentialList: [],
      organizationId: null,
      organizationName: null,
      processFlg: true,
      deviceFlg: true,
      clampFlg: true,
      personnelFlg: true,
      saveLoading: false,
      loading: null, // 用于存储loading实例
      rules: {
        realityLineName: [
          { required: true, message: "请输入产线模板名称", trigger: "blur" },
        ],
        lineType: [
          { required: true, message: "请输入产线类型", trigger: "blur" },
        ],
        productCategory: [
          { required: true, message: "请输入产品分类", trigger: "blur" },
        ],
        lineIndicator: [
          { required: true, message: "请输入线平衡率", trigger: "blur" },
        ],
        station: [{ required: true, message: "请输入工位", trigger: "blur" }],
      },
      editWorkVisible: false,
      workform: {
        station: [],
      },
      person_grades: [],
      line_type: [],
    };
  },
  created() {
    //获取当前工厂信息
    this.getFactoryInfo();
    //获取车间集合
    this.getWorkshopListData();
    //获取所有人员数据
    this.getPersonCredentialListData();
    // 获取产线类型数据
    this.getCategoryData();
    // 获取工序名称数据
    this.getProcessListData();
    this.getWorkPositionLists();
    this.getPersonGradesList();
    this.getLineTypeList();
  },
  computed: {
    availableHeight() {
      return window.innerHeight - 400;
    },
  },
  props: {
    lineId: {
      type: String,
      default: "",
    },
    addDialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.addDefaultRows();
  },

  watch: {
    addDialogVisible: {
      handler(newVal) {
        if (newVal) {
          this.form = {
            realityLineName: "",
            lineType: "",
            productCategory: "",
            lineIndicator: "",
          };
          this.tableList = [];
          if (this.lineId) {
            this.getDetails();
          }
        }
      },
      immediate: true, // 立即执行
    },
  },

  methods: {
    handleLineIndicatorChange(value) {
      if (value !== "") {
        this.form.lineIndicator = parseFloat(value).toFixed(2);
      }
    },
    getLineTypeList() {
      getLineType().then((response) => {
        this.line_type = response.data.data;
      });
    },
    getDetails() {
      this.saveLoading = true;
      getAllObj(this.lineId).then((res) => {
        this.saveLoading = false;

        this.form.realityLineName = res.data.data.realityLineName;
        this.form.lineType = res.data.data.lineType;
        this.form.productCategory = res.data.data.productCategory;
        this.form.lineIndicator = res.data.data.lineIndicator;
        this.tableList = res.data.data.detailsList;
        /*this.tableList = res.data.data.detailsList.map((item) => {
          return {
            ...item,
            workPositionDataList: item.workPositionDataList.map((ii) => {
              return {
                ...ii,
                personGradesArray: ii.personGradesArray ? ii.personGradesArray.split(",") : [],
              };
            }),
          };
        });*/
      });
    },
    preAddstation() {
      this.workform.station.forEach((item) => {
        this.preAddstationExe(item);
      });
    },
    preAddstationExe(stationItem) {
      getWorkPositionData(stationItem).then((response) => {
        const { id, workPositionName, workPositionProcessList } =
          response.data.data;
        let newList = workPositionProcessList.map((item) => {
          return {
            processId: item.processId,
            processName: item.processName,
            deviceTypeArray: [], //设备类型
            deviceNum: 0, //设备数量
            toolTypeArray: [], //工具类型
            toolNum: 0, //工具数量
            clampTypeArray: [], //夹具类型
            clampNum: 0, //夹具数量
            personGradesArray: [], //人员资质等级
            personNum: 0, //人员数量
            sortOrder: item.sortOrder, //排序值
          };
        });

        this.tableList.push({
          id: "", //主键id
          workPositionId: id, //工位ID
          workPositionName: workPositionName, //工位名称
          workPositionDataList: newList,
        });

        this.workform.station = [];

        this.editWorkVisible = false;
      });
    },
    changeProcess(item) {},

    async getWorkPositionLists() {
      let data = { parentId: "1937538060729290753" };
      const res = await getWorkPositionList(data);
      this.workPositionList = [
        ...res.data.data.map((item) => {
          return {
            value: item.id,
            label: item.workPositionName,
          };
        }),
      ];
    },
    addDefaultRows() {
      for (let i = 0; i < 10; i++) {
        this.tableData.push({
          processName: "",
          workPositionName: "",
          equipment: "",
          deviceShowOption: false,
          fixture: [], // 修改为数组类型
          fixtureShowOption: false,
          personnel: [], // 修改为数组类型，支持多选
          personnelShowOption: false,
        });
      }
    },
    /**获取工厂信息*/
    getFactoryInfo() {
      const factoryId = 1;
      getObj(factoryId).then((response) => {
        this.organizationId = response.data.data.menuId; //组织ID
        this.organizationName = response.data.data.organizationName; //组织名称
        //获取工厂设备集合
        this.getFactoryDeviceList();
      });
    },
    getPersonGradesList() {
      getPersonGrades().then((response) => {
        this.person_grades = response.data.data;
      });
    },
    /**获取工厂设备集合*/
    getFactoryDeviceList() {
      var obj = {
        position: this.organizationName, //设置组织查询条件
        groupFlag: true,
      };
      getNewDevice(obj).then((response) => {
        this.deviceList = response.data.data; //设备集合
        for (var i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].deviceClass === "20") {
            //组织下工具夹具筛选
            this.clampList.push(this.deviceList[i]); //夹具集合
            this.toolList.push(this.deviceList[i]); //工具集合
          }
        }
        this.deviceFlg = false;
        this.clampFlg = false;
      });
    },
    /**获取车间集合*/
    getWorkshopListData() {
      getWorkshopList().then((response) => {
        this.workshopList = response.data.data;
      });
    },
    /**车间选择*/
    workshopChange(row) {
      this.workshopName = row.workshopName; //车间名称
    },
    //获取所有人员数据
    getPersonCredentialListData() {
      getPersonCredentialList().then((response) => {
        this.personCredentialList = response.data.data.map((item) => {
          return {
            jobNo: item.jobNo,
            personName: item.personName,
          };
        });

        // this.personCredentialList = response.data.data;
        this.personnelFlg = false;
      });
    },
    // 获取产线类型数据
    async getCategoryData() {
      getCategory().then((response) => {
        this.categoryList = response.data.data;
      });
    },
    // 获取工序名称数据
    async getProcessListData() {
      getPfocProcessList().then((response) => {
        this.processList = response.data.data;
        this.processFlg = false;
      });
    },
    downloadTemplate() {
      downBlobFile(
        "/pfoc/craftproduct/local/file/产线建模导入.xlsx",
        "",
        "产线建模导入.xlsx"
      );
    },

    addRow() {
      this.editWorkVisible = true;
    },
    importExcel() {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".xlsx, .xls";
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          // 显示加载提示
          this.loading = this.$loading({
            lock: true,
            text: "正在解析数据，请稍候...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          const reader = new FileReader();
          reader.onload = (event) => {
            const data = event.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            const newTableData = [];
            const unimportedInfo = [];

            jsonData.forEach((item) => {
              const fixtureCodes = (item["夹具编码"] || "")
                .split(",")
                .map((s) => s.trim());
              const personnelCodes = String(item["员工号"] || "")
                .split(",")
                .map((s) => s.trim());
              const processName = item["工序名称"] || "";
              const workPositionName = item["工位"] || "";
              const equipmentCodes = (item["设备编码"] || "")
                .split(",")
                .map((s) => s.trim()); // 处理多选设备编码

              const unmatchedFixtures = [];
              const unmatchedPersonnel = [];
              let unmatchedProcess = null;
              let unmatchedworkPosition = null;
              let unmatchedEquipment = []; // 修改为数组类型，支持多个未匹配设备

              const validFixtureCodes = fixtureCodes.filter((code) => {
                const clamp = this.clampList.find((c) => c.deviceSn === code);
                if (!clamp) {
                  unmatchedFixtures.push(code);
                  return false;
                }
                return true;
              });

              const validPersonnelCodes = personnelCodes.filter((code) => {
                const person = this.personCredentialList.find(
                  (p) => p.jobNo === code
                );
                if (!person) {
                  unmatchedPersonnel.push(code);
                  return false;
                }
                return true;
              });

              const process = this.processList.find(
                (p) => p.processName === processName
              );
              if (!process) {
                unmatchedProcess = processName;
              }

              const workPosition = this.workPositionList.find(
                (p) => p.label === workPositionName
              );
              if (!workPosition) {
                unmatchedworkPosition = workPositionName;
              }

              const validEquipmentCodes = equipmentCodes.filter((code) => {
                const equipment = this.deviceList.find(
                  (d) => d.deviceSn === code
                );
                if (!equipment) {
                  unmatchedEquipment.push(code);
                  return false;
                }
                return true;
              });

              newTableData.push({
                processName: process ? processName : "",
                workPositionName: workPosition ? workPositionName : "",
                workPositionId: workPosition ? workPosition.value : "",
                equipment: validEquipmentCodes, // 存储多选设备编码
                fixture: validFixtureCodes,
                personnel: validPersonnelCodes,
                fixtureShowOption: true,
                personnelShowOption: true,
                deviceShowOption: true,
              });

              if (unmatchedProcess) {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：工序名称 [${unmatchedProcess}] 未匹配到`
                );
              }
              if (unmatchedworkPosition) {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：工位名称 [${unmatchedworkPosition}] 未匹配到`
                );
              }
              if (unmatchedEquipment.length > 0) {
                unmatchedEquipment.forEach((code) => {
                  unimportedInfo.push(
                    `第 ${item["序号"]} 行：设备编码 [${code}] 未匹配到`
                  );
                });
              }
              unmatchedFixtures.forEach((code) => {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：夹具编码 [${code}] 未匹配到`
                );
              });
              unmatchedPersonnel.forEach((code) => {
                unimportedInfo.push(
                  `第 ${item["序号"]} 行：员工号 [${code}] 未匹配到`
                );
              });
            });

            this.tableData = newTableData;
            this.$nextTick(() => {
              this.tableData.forEach((item) => {
                item.fixtureShowOption = false;
                item.personnelShowOption = false;
                item.deviceShowOption = false;
              });
            });
            if (unimportedInfo.length > 0) {
              const unimportedDataStr = unimportedInfo.join("<br>");
              this.$confirm(
                `以下数据部分字段未导入：<br>${unimportedDataStr}`,
                "提示",
                {
                  confirmButtonText: "确定",
                  customClass: "custom-confirm-dialog", // 添加自定义类名
                  type: "warning",
                  dangerouslyUseHTMLString: true,
                }
              )
                .then(() => {
                  // 点击确认后关闭弹框
                })
                .catch(() => {
                  // 取消操作，不做任何处理
                });
            }
            // 数据解析完成，关闭加载提示
            this.loading.close();
          };
          reader.readAsBinaryString(file);
        }
      };
      input.click();
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.cormSubmit();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      // // 验证产线名称、车间、产线类型是否为空
      // // if (!this.form.lineName) {
      // //   this.$message.error("产线名称不能为空");
      // //   return;
      // // }
      // // if (!this.workshopId) {
      // //   this.$message.error("车间不能为空");
      // //   return;
      // // }
      // // if (!this.form.lineType) {
      // //   this.$message.error("产线类型不能为空");
      // //   return;
      // // }
      // // 验证列表是否包含一条工序数据
      // if (
      //   this.tableData.length === 0 ||
      //   this.tableData.every((row) => !row.processName)
      // ) {
      //   this.$message.error("列表必须包含一条工序数据");
      //   return;
      // }
      // // 验证列表每一行如果有一个填写了就必须把剩余的都填写完成
      // for (let i = 0; i < this.tableData.length; i++) {
      //   const row = this.tableData[i];
      //   const hasAnyValue =
      //     row.processName ||
      //     row.equipment.length > 0 ||
      //     row.fixture.length > 0 ||
      //     row.personnel.length > 0;
      //   if (hasAnyValue) {
      //     if (!row.processName) {
      //       this.$message.error(`第 ${i + 1} 行工序名称未填写`);
      //       return;
      //     }
      //     // if (row.equipment.length === 0) {
      //     //   this.$message.error(`第 ${i + 1} 行设备未填写`)
      //     //   return
      //     // }
      //     // if (row.fixture.length === 0) {
      //     //   this.$message.error(`第 ${i + 1} 行夹具未填写`)
      //     //   return
      //     // }
      //     // if (row.personnel.length === 0) {
      //     //   this.$message.error(`第 ${i + 1} 行人员未填写`)
      //     //   return
      //     // }
      //   }
      // }
      // const dataToSave = {
      //   realityLineName: this.form.lineName,
      //   workshopId: this.workshopId, // 使用选中的车间ID
      //   workshopName: "",
      //   lineType: this.form.lineType,
      //   deviceSnStr: "",
      //   list: [],
      // };
      // // 根据ID获取车间名称
      // const workshop = this.workshopList.find((w) => w.id === this.workshopId);
      // if (workshop) {
      //   dataToSave.workshopName = workshop.workshopName;
      // }
      // let deviceSnStr = "";
      // // 处理 list 数据，剔除空数据行
      // this.tableData.forEach((row, index) => {
      //   const hasData =
      //     row.processName ||
      //     row.equipment.length > 0 ||
      //     row.fixture.length > 0 ||
      //     row.personnel.length > 0;
      //   if (hasData) {
      //     const item = {
      //       processId: "", // 假设这里没有提供工序ID的获取逻辑，先设为空字符串
      //       processName: row.processName,
      //       workPositionName: this.workPositionList.find(
      //         (d) => d.value == row.workPositionId
      //       ).label,
      //       workPositionId: row.workPositionId,
      //       nodeId: index + 1, // 假设这里没有提供排序的获取逻辑，先设为空字符串
      //       device: row.equipment.join(","), // 拼接多选设备编码
      //       deviceNames: "",
      //       clamp: "",
      //       clampNames: "",
      //       workshopSection: "",
      //       jobNo: "",
      //     };
      //     // 根据设备编码获取设备名称
      //     const devices = row.equipment.map((code) =>
      //       this.deviceList.find((d) => d.deviceSn === code)
      //     );
      //     item.deviceNames = devices
      //       .filter(Boolean)
      //       .map((d) => d.deviceName)
      //       .join(",");
      //     deviceSnStr = deviceSnStr + row.equipment.join(",") + ",";
      //     // 获取选中工序id
      //     const process = this.processList.find(
      //       (d) => d.processName === row.processName
      //     );
      //     if (process) {
      //       item.processId = process.id;
      //       item.workshopSection = process.workshopSection;
      //     }
      //     // 处理夹具编码和名称
      //     item.clamp = row.fixture
      //       .map((f) => {
      //         const parts = f.match(/\((.*)\)/);
      //         return parts ? parts[1] : f;
      //       })
      //       .join(",");
      //     // 循环 clamp 去 clampList 匹配 deviceName 并拼接
      //     const clampNamesArray = [];
      //     row.fixture.forEach((fixture) => {
      //       const parts = fixture.match(/\((.*)\)/);
      //       const fixtureSn = parts ? parts[1] : fixture;
      //       const foundClamp = this.clampList.find(
      //         (c) => c.deviceSn === fixtureSn
      //       );
      //       if (foundClamp) {
      //         clampNamesArray.push(foundClamp.deviceName);
      //       }
      //     });
      //     item.clampNames = clampNamesArray.join(",");
      //     // 处理人员数据
      //     item.jobNo = row.personnel.join(",");
      //     dataToSave.list.push(item);
      //   }
      // });
      // //判断deviceSnStr不为空截取最后一个逗号
      // if (deviceSnStr.length > 0) {
      //   deviceSnStr = deviceSnStr.substring(0, deviceSnStr.length - 1);
      // }
      // dataToSave.deviceSnStr = deviceSnStr;
      // this.saveLoading = true;
      // saveProductLine(dataToSave)
      //   .then((response) => {
      //     if (response.data.code === 0) {
      //       this.$message.success("保存成功");
      //       this.handleClose();
      //     } else {
      //       this.$message.error("保存失败：" + response.data.message);
      //     }
      //   })
      //   .catch((error) => {
      //     this.saveLoading = false;
      //     console.error("保存请求出错", error);
      //     this.$message.error("保存过程中出现错误，请检查网络或重试");
      //   });
    },
    cormSubmit() {
      /*let nList = this.tableList.map((item) => {
        return {
          ...item,
          workPositionDataList: item.workPositionDataList.map((ii) => {
            return {
              ...ii,
              //personGradesArray: ii.personGradesArray.join(","),
            };
          }),
        };
      });*/

      let data = { ...this.form, detailsList: this.tableList, id: this.lineId };

      if (this.lineId) {
        putObj(data).then((res) => {
          if (res) {
            this.$message.success("保存成功");
            this.handleClose();
          }
        });
      } else {
        addObj(data).then((res) => {
          if (res) {
            this.$message.success("新增成功");
            this.handleClose();
          }
        });
      }
    },
    moveUp(index) {
      // 新增行空值不能上移
      // const row = this.tableData[index];
      // if (
      //   index > 0 &&
      //   (row.processName ||
      //     row.equipment ||
      //     row.fixture.length > 0 ||
      //     row.personnel.length > 0)
      // ) {
      //   const temp = this.tableData[index];
      //   this.tableData.splice(index, 1);
      //   this.tableData.splice(index - 1, 0, temp);
      // }

      if (index > 0) {
        const temp = this.tableList[index];
        this.tableList.splice(index, 1);
        this.tableList.splice(index - 1, 0, temp);
      }
    },
    moveDown(index) {
      // if (index < this.tableData.length - 1) {
      //   const currentRow = this.tableData[index];
      //   const nextRow = this.tableData[index + 1];
      //   const currentRowHasData =
      //     currentRow.processName ||
      //     currentRow.equipment ||
      //     currentRow.fixture.length > 0 ||
      //     currentRow.personnel.length > 0;
      //   const nextRowHasData =
      //     nextRow.processName ||
      //     nextRow.equipment ||
      //     nextRow.fixture.length > 0 ||
      //     nextRow.personnel.length > 0;
      //   if (currentRowHasData && nextRowHasData) {
      //     const temp = this.tableData[index];
      //     this.tableData.splice(index, 1);
      //     this.tableData.splice(index + 1, 0, temp);
      //   }
      // }

      if (index < this.tableList.length - 1) {
        const temp = this.tableList[index];
        this.tableList.splice(index, 1);
        this.tableList.splice(index + 1, 0, temp);
      }
    },
    deleteRow(index) {
      this.tableList.splice(index, 1);
    },
    handleClose() {
      this.saveLoading = false;
      this.$emit("closeAdd"); //关闭新增页面
    },
  },
};
</script>

<style scoped>
::v-deep .my-import-button {
  position: relative;
}
::v-deep .my-cancel-button {
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
/* 为弹窗添加自定义样式 */
.custom-confirm-dialog .el-message-box__message {
  max-height: 400px !important; /* 设置弹窗最大高度 */
  overflow-y: auto !important; /* 当内容超出最大高度时显示垂直滚动条 */
}
.footer {
  display: flex;
  margin-top: 20px;
  position: fixed;
  bottom: 20px;
}
.form {
  display: flex;
  align-items: center;
  margin: 10px;
  padding-top: 20px;
  background-color: #fff;
}
.container-box {
  background-color: #f6f7fa;
  overflow: auto; /* 或者 hidden、scroll */
}
.table-box {
  position: relative;
  top: 0px;
  margin: 0 10px 10px 10px;
  padding: 10px;
  background-color: #fff;
}
</style>
